package com.talking.view.chat;

import com.talking.controller.chat.SendChatMsgController;
import com.talking.view.component.*;
import com.talking.view.componentpojo.BodyFrameObj;
import com.talking.view.componentpojo.ChatPojo;
import com.talking.view.componentpojo.ColorObj;
import com.talking.view.componentpojo.JScrollPaneConfig;
import jdk.nashorn.internal.ir.Block;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

//右边的面板
public class RightPanel extends JPanel {

    private CardLayout rightCardLayout;             //右边面板的卡片布局
    private JLabel logoLabel;               //logo面板
    private JPanel messageSendPanel;        //消息面板，包含聊天窗，消息窗

    private TopPanel topPanel;                      //顶部名字面板
    private JScrollPane showJScroll;          //中间层的聊天滚动面板
    private JPanel bottomPanel;                      //发送消息面板

    private ToolPanel toolPanel;                  //表情包面板
    private EmjioWidow emjioWidow;              //表情包内容窗口

    private JScrollPane sendJScroll;                //发送消息面板文本框滚动条
    private SendButtonPanel sendMsgButton;              //发送按钮面板
    private JLabel emjioLabel;                      //表情包按钮


    //右边面板的全局组件
    private JPanel showPane;
    private JIMSendTextPane sendPane;                   //消息发送框

    //好友信息窗口
    private FriendMsgWindow friendMsgWindow;

    private List<EmjioTemp> emjioTempList = new ArrayList<>();
    private int caretPosition;              //输入框光标位置


    public RightPanel(){

        rightCardLayout = new CardLayout();
        logoLabel = new JLabel(new ImageIcon("image/logo/logo200x200.png"));
        messageSendPanel = new JPanel();
        topPanel = new TopPanel();
        friendMsgWindow = new FriendMsgWindow(BodyFrameObj.getBodyFrame());
//        showPane = new JIMSendTextPane();
//        showJScroll = new JScrollPane(showPane);
        showPane = new JPanel();
        showPane.setLayout(new VerticalFlowLayout());
        showPane.setBackground(ColorObj.MAIN_BACKGROUND);
        showJScroll = new JScrollPane(showPane);

        bottomPanel = new JPanel();
        toolPanel = new ToolPanel();
        emjioLabel = new JLabel(new ImageIcon("image/chat/emjio1.png"));
        emjioWidow = new EmjioWidow(BodyFrameObj.getBodyFrame());


        sendPane = new JIMSendTextPane();
        sendJScroll = new JScrollPane(sendPane);
        sendMsgButton = new SendButtonPanel();

//        showPane.setEditable(false);
        JScrollPaneConfig.setUI(showJScroll);

        this.setLayout(rightCardLayout);


        //消息发送面板的东西
        messageSendPanel.setLayout(new BorderLayout());

        //底部发送信息面板
        emjioLabel.setBounds(20,5,25,25);
        bottomPanel.setPreferredSize(new Dimension(1,200));
        bottomPanel.setLayout(new BorderLayout());
        bottomPanel.setBackground(ColorObj.MAIN_BACKGROUND);
        toolPanel.setPreferredSize(new Dimension(1,40));
        sendPane.setPreferredSize(new Dimension(1,100));
        JScrollPaneConfig.setUI(sendJScroll);

        sendMsgButton.setPreferredSize(new Dimension(1,60));

        toolPanel.setLayout(null);
        toolPanel.add(emjioLabel);

        messageSendPanel.add(topPanel, BorderLayout.NORTH);
        messageSendPanel.add(showJScroll,BorderLayout.CENTER);
        messageSendPanel.add(bottomPanel,BorderLayout.SOUTH);

        bottomPanel.add(toolPanel,BorderLayout.NORTH);
        JLabel t = new JLabel();
        t.setPreferredSize(new Dimension(20,1));
        bottomPanel.add(t, BorderLayout.WEST);
        bottomPanel.add(sendJScroll,BorderLayout.CENTER);
        bottomPanel.add(sendMsgButton,BorderLayout.SOUTH);

        this.add(logoLabel,"0");
        this.add(messageSendPanel,"1");

        this.setBackground(ColorObj.MAIN_BACKGROUND);
        BodyFrameObj.setEmjioWindow(emjioWidow);
        BodyFrameObj.setFriendMsgWindow(friendMsgWindow);

        emjioLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                emjioLabel.setIcon(new ImageIcon("image/chat/emjio2.png"));
                caretPosition = sendPane.getCaretPosition();
                repaint();
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                emjioLabel.setIcon(new ImageIcon("image/chat/emjio1.png"));
                repaint();
                JFrame jFrame = BodyFrameObj.getBodyFrame();
                emjioWidow.setBounds(jFrame.getX()+350,jFrame.getY()+jFrame.getHeight()-400,500,200);
                emjioWidow.setFocusableWindowState(true);
                emjioWidow.requestFocus();
                emjioWidow.setVisible(true);
            }
        });

        sendPane.addKeyListener(new MyKeyListener());

        //设置静态对象
        ChatPojo.setRightPanel(this);
        ChatPojo.setRightCard(rightCardLayout);
        ChatPojo.setTopPanel(topPanel);
//        ChatPojo.setShowPane(showPane);
        ChatPojo.setMsgShow(showPane);
        ChatPojo.setSendPane(sendPane);
        ChatPojo.setMsgJScroll(showJScroll);

//        showJScroll.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
//            @Override
//            public void adjustmentValueChanged(AdjustmentEvent e) {
//                e.getAdjustable().setValue(e.getAdjustable().getMaximum());
//            }
//        });
    }

    public void packageSendMSG(){
        StringBuffer stringBuffer = new StringBuffer(sendPane.getText());
        EmjioTemp[] emjioTemps = new EmjioTemp[emjioTempList.size()];

        int temp1 = 0;
        for (EmjioTemp emjioTemp : emjioTempList) {
            emjioTemps[temp1] = emjioTemp;
            temp1++;
        }

        for (int i=0;i<emjioTemps.length-1;i++){
            for (int j=0;j<emjioTemps.length-1-i;j++){
                EmjioTemp temp = null;
                if (emjioTemps[j].position>emjioTemps[j+1].position) {
                    temp = emjioTemps[j];
                    emjioTemps[j] = emjioTemps[j+1];
                    emjioTemps[j+1] = temp;
                }
            }
        }

        for (int i = 0; i < emjioTemps.length; i++) {
            System.out.println(emjioTemps[i].toString());
        }

        for (int i = emjioTemps.length-1; i >=0 ; i--) {
            stringBuffer.replace(emjioTemps[i].position,emjioTemps[i].position+1,emjioTemps[i].content);
        }
        System.out.println(stringBuffer.toString());


        new SendChatMsgController(stringBuffer.toString(),sendPane,ChatPojo.getBlockPanel());
        emjioTempList.removeAll(emjioTempList);

    }

    //这个类用来处理表情包与文字
    private class MyKeyListener extends KeyAdapter {
        private int banTwoButton=0;

        @Override
        public void keyPressed(KeyEvent e) {
            System.out.println("Press监听"+e.getKeyCode());
            int position = sendPane.getCaretPosition();          //光标位置

            banTwoButton = e.getKeyCode();
            //仅仅处理删除键与回车键
            if (e.getKeyCode()==8){
                System.out.println("press检测到删除键");
                int start = sendPane.getSelectionStart();
                int end = sendPane.getSelectionEnd();
                int selectTextCount = end-start;

                if (start==end&&position!=0) {            //是否是单个删除
                    System.out.println("单个删除");

                    for (int i = 0,countTemp = 0; countTemp < emjioTempList.size()&&emjioTempList.size()!=0; i++,countTemp++) {

                        EmjioTemp emjioTemp = emjioTempList.get(i);


                        if (position <= emjioTemp.position) {
                            System.out.println("字符删除");
                            System.out.println("光标位置是：" + position + ",表情包位置：" + emjioTemp.position);
                            System.out.println("删除前长度：" + emjioTempList.size());
                            emjioTempList.remove(i);
                            System.out.println("删除后的长度：" + emjioTempList.size());
                            i--;
                            emjioTempList.add(new EmjioTemp(emjioTemp.position-1,emjioTemp.content));
                            System.out.println("增加后的长度：" + emjioTempList.size());

                            for (EmjioTemp emjioTemp1 : emjioTempList) {
                                System.out.println(emjioTemp1.toString());
                            }
                        } else if (position == emjioTemp.position + 1) {
                            System.out.println("执行了删除单个表情包：");
                            //移除自己，并且后面每一个元素的坐标都-1
                            emjioTempList.remove(i);

                            i--;
                            countTemp--;
                        }
                    }

                }else {     //选择删除
                    System.out.println("选择性删除判断");
                    if (position==0&&end==sendPane.getText().length()) {            //全选删除
                        System.out.println("全删");
                        emjioTempList.removeAll(emjioTempList);
                    } else{
                        System.out.println("非全选");
                        for (int i = 0,temp=0; temp < emjioTempList.size()&&emjioTempList.size()!=0; i++,temp++) {
                            EmjioTemp emjioTemp = emjioTempList.get(i);
                            if (start <= emjioTemp.position) {
                                if (end <= emjioTemp.position) {
                                    System.out.println("结束光标在左边");
                                    System.out.println("光标位置是：" + position + ",表情包位置：" + emjioTemp.position);
                                    emjioTemp.position -= selectTextCount;
                                    emjioTempList.remove(i);
                                    i--;
                                    emjioTempList.add(emjioTemp);
                                    for (EmjioTemp emjioTemp1 : emjioTempList) {
                                        System.out.println(emjioTemp1.toString());
                                    }
                                } else {
                                    System.out.println("结束光标在右边");
                                    System.out.println("光标位置是：" + position + ",表情包位置：" + emjioTemp.position);
                                    emjioTempList.remove(i);
                                    i--;
                                    temp--;
                                    for (EmjioTemp emjioTemp1 : emjioTempList) {
                                        System.out.println(emjioTemp1.toString());
                                    }
                                }
                            }
                        }

                    }
                }
            }else if (e.getKeyCode()==10) {
                e.consume();
                packageSendMSG();
            }
        }



        @Override
        public void keyTyped(KeyEvent e){
            int keyCode = e.getKeyChar();           //键入事件无法获取keycode
            int position = sendPane.getCaretPosition();
            int start = sendPane.getSelectionStart();
            int end = sendPane.getSelectionEnd();
            int selectTextCount = end-start;


            System.out.println("\n这是Type监听,监听KeyChar是："+keyCode+"按钮");

            if (keyCode!=8&&keyCode!=10&&banTwoButton==keyCode){
                if (start==end){            //单选
                    System.out.println("插入一个字符");

                    for (int i = 0,temp=0; temp < emjioTempList.size()&&emjioTempList.size()!=0; i++,temp++) {
                        EmjioTemp emjioTemp = emjioTempList.get(i);

                        if (position<=emjioTemp.position){
                            System.out.println("单个字符增加");
                            System.out.println("光标位置是：" + position + ",表情包位置：" + emjioTemp.position);
                            System.out.println("删除前长度：" + emjioTempList.size());
                            emjioTempList.remove(i);
                            System.out.println("删除后的长度：" + emjioTempList.size());
                            i--;
                            emjioTempList.add(new EmjioTemp(emjioTemp.position+1,emjioTemp.content));
                            System.out.println("增加后的长度：" + emjioTempList.size());

                            for (EmjioTemp emjioTemp1 : emjioTempList) {
                                System.out.println(emjioTemp1.toString());
                            }
                        }
                    }

                }else {
                    System.out.println("一段字符变成一个字符");

                    if (position==0&&end==sendPane.getText().length()) {            //全选删除
                        System.out.println("全部选中");
                        emjioTempList.removeAll(emjioTempList);
                    } else{
                        System.out.println("非全选");

                        for (int i = 0,temp=0; temp < emjioTempList.size()&&emjioTempList.size()!=0; i++,temp++) {
                            EmjioTemp emjioTemp = emjioTempList.get(i);
                            if (start <= emjioTemp.position) {
                                if (end <= emjioTemp.position) {
                                    System.out.println("结束光标在左边");
                                    System.out.println("光标位置是：" + position + ",表情包位置：" + emjioTemp.position);
                                    emjioTemp.position = emjioTemp.position - selectTextCount+1;
                                    emjioTempList.remove(i);
                                    i--;
                                    emjioTempList.add(emjioTemp);
                                    for (EmjioTemp emjioTemp1 : emjioTempList) {
                                        System.out.println(emjioTemp1.toString());
                                    }
                                } else {
                                    System.out.println("结束光标在右边");
                                    System.out.println("光标位置是：" + position + ",表情包位置：" + emjioTemp.position);
                                    emjioTempList.remove(i);
                                    i--;
                                    temp--;
                                    for (EmjioTemp emjioTemp1 : emjioTempList) {
                                        System.out.println(emjioTemp1.toString());
                                    }
                                }
                            }
                        }

                    }

                }
            }

        }
    }
    private class EmjioTemp{
        private int position;
        private String content;
        public EmjioTemp(int position,String content){
            this.position = position;
            this.content = content;
        }

        @Override
        public String toString() {
            return "EmjioTemp{" +
                    "position=" + position +
                    ", content='" + content + '\'' +
                    '}';
        }
    }

    //表情包的弹窗
    private class EmjioWidow extends JWindow{
        private JLabel jLabelShadow;           //阴影面板
        private JScrollPane jScrollPane;       //滚动面板
        private JPanel jPanelContent;          //内容面板
        public EmjioWidow(JFrame jFrame){
            super(jFrame);
            jLabelShadow = new JLabel();
            jPanelContent = new JPanel();
            jScrollPane = new JScrollPane(jPanelContent);

            this.setSize(new Dimension(500,200));
            this.setBackground(new Color(0,0,0,0));
            this.setFocusable(true);
            jPanelContent.setBackground(Color.black);
            jLabelShadow.setBorder(new ShadowBorder(10));
            jLabelShadow.setLayout(null);
            jPanelContent.setBackground(ColorObj.MAIN_BACKGROUND);
            jScrollPane.getVerticalScrollBar().setUnitIncrement(15);
            jScrollPane.getVerticalScrollBar().setUI(new MyScrollBarUI());
            jScrollPane.setBorder(null);
            jScrollPane.setHorizontalScrollBarPolicy(jScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            jScrollPane.setVerticalScrollBarPolicy(jScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            jScrollPane.setBounds(13,13,474,174);

            GridLayout gridLayout = new GridLayout(5,7);
            gridLayout.setVgap(10);
            jPanelContent.setLayout(gridLayout);
            for (int i = 0; i < 31; i++) {
                jPanelContent.add(new DetailEmjio(i));
            }

            jLabelShadow.add(jScrollPane, BorderLayout.CENTER);
            this.add(jLabelShadow);
            this.addWindowFocusListener(new WindowAdapter() {
                @Override
                public void windowLostFocus(WindowEvent e) {
                    dispose();
                }
            });
        }
    }

    //每一个表情包
    private class DetailEmjio extends JLabel{
        private int num;
        private List<String> emjioName;
        private String code;
        public DetailEmjio(int num){
            this.num = num;
            emjioName = new ArrayList();

            File imagePath = new File("image/chat/emjio");
            File[] allPng = imagePath.listFiles();
            for (File file : allPng) {
                emjioName.add(file.getName());
            }

            setIcon(new ImageIcon("image/chat/emjiomin/"+emjioName.get(num)));
            this.setToolTipText(emjioName.get(num).replace(".png",""));
            this.setPreferredSize(new Dimension(40,40));

            this.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseEntered(MouseEvent e){

                    setIcon(new ImageIcon("image/chat/emjio/"+emjioName.get(num)));
                }
                @Override
                public void mouseExited(MouseEvent e){
                    setIcon(new ImageIcon("image/chat/emjiomin/"+emjioName.get(num)));
                }
                @Override
                public void mouseClicked(MouseEvent e) {
                    sendPane.setCaretPosition(caretPosition);
                    Font f = new Font("黑体",Font.PLAIN,24);
                    FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(f);
                    ImageIcon imageIcon = new ImageIcon("image/chat/emjio/"+emjioName.get(num));
                    imageIcon.setImage(imageIcon.getImage().getScaledInstance(fm.getHeight(),fm.getHeight(),Image.SCALE_DEFAULT));
                    sendPane.insertIcon(imageIcon);
                    emjioTempList.add(new EmjioTemp(caretPosition,emjioName.get(num).replace(".png","")));
//                    }
                }
            });
        }
    }

    //顶部的名字面板
    public class TopPanel extends JPanel{
        public JLabel userNameLabel;
        private PersonPanel null2;
        public TopPanel(){
            userNameLabel = new JLabel("暂无用户");
            null2 = new PersonPanel();

            this.setLayout(new BorderLayout());
            userNameLabel.setFont(new Font("黑体",Font.PLAIN,22));
            userNameLabel.setHorizontalAlignment(SwingConstants.CENTER);
            this.add(userNameLabel,BorderLayout.CENTER);
            this.add(null2,BorderLayout.EAST);
            this.setPreferredSize(new Dimension(1,50));
            this.setBackground(ColorObj.MAIN_BACKGROUND);
        }
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.setColor(ColorObj.splitLineColor);
            g.drawLine(0,this.getHeight()-1,this.getWidth(),this.getHeight()-1);
        }
        public void setUserName(String name){
            userNameLabel.setText(name);
        }
    }

    //顶部面板的三个点点
    private class PersonPanel extends JLabel{
        private Color buttonColor;
        public PersonPanel(){
            buttonColor = ColorObj.buttonReleasedColor;
            this.setPreferredSize(new Dimension(50,50));
            this.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    buttonColor = ColorObj.mainThemeColor;
                    PersonPanel.this.repaint();
                }

                @Override
                public void mouseReleased(MouseEvent e) {
//                    JFrame jFrame = BodyFrameObj.getBodyFrame();
//                    friendMsgWindow.setLocation(jFrame.getX()+jFrame.getWidth()-340,jFrame.getY()+40);
//                    new FriendMsgController(friendMsgWindow).setContent();
//                    friendMsgWindow.setVisible(true);
                    friendMsgWindow.showWindow();
                    buttonColor = ColorObj.buttonReleasedColor;
                    PersonPanel.this.repaint();
                }
            });
        }
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.setColor(buttonColor);
            for (int i = 0; i < 3; i++) {
                g.fillOval(5+i*10,22,5,5);
            }
        }
    }
    private class ToolPanel extends JPanel{
        public void paintComponent(Graphics g){
            g.setColor(ColorObj.splitLineColor);
            g.drawLine(0,1,this.getWidth(),1);
        }
    }
    private class SendButtonPanel extends JPanel{
        private SendButton sendButton;
        public SendButtonPanel(){
            sendButton = new SendButton();
            sendButton.setPreferredSize(new Dimension(120,40));
            this.setLayout(new BorderLayout());
            this.setBackground(ColorObj.MAIN_BACKGROUND);

            this.add(new JLabel(),BorderLayout.CENTER);
            this.add(sendButton,BorderLayout.EAST);

        }
    }

    //发送按钮
    private class SendButton extends JLabel{
        private Color buttonTextColor;
        public SendButton(){
            this.setBackground(ColorObj.MAIN_BACKGROUND);
            buttonTextColor = ColorObj.buttonReleasedColor;
            this.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    buttonTextColor = Color.BLACK;
                    repaint();
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    buttonTextColor = ColorObj.buttonReleasedColor;
                    repaint();
                    packageSendMSG();
                }
            });
        }
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            Graphics2D draw = (Graphics2D)g;                                                            //抗锯齿
            draw.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            draw.setColor(ColorObj.buttonReleasedColor);

            draw.drawArc(2,0,39,39,90,180);
            draw.drawArc(3,1,37,37,90,180);
            draw.drawLine(21,0,59,0);
            draw.drawLine(21,1,59,1);
            draw.drawLine(21,39,59,39);
            draw.drawLine(21,38,59,38);
            draw.drawArc(39,1,37,37,270,180);
            draw.drawArc(38,0,39,39,270,180);

            draw.setColor(buttonTextColor);
            draw.setFont(new Font("等线",Font.BOLD,20));
            draw.drawString("发送",20,26);
        }
    }
}
